package com.example.boot.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.boot.enums.MsgSignFlagEnum;
import com.example.boot.mapper.ChatMsgMapper;
import com.example.boot.mapper.UsersMapper;
import com.example.boot.mapper.UsersMapperCustom;
import com.example.boot.netty.entity.ChatMessage;
import com.example.boot.pojo.ChatMsg;
import com.example.boot.pojo.Users;
import com.example.boot.pojo.vo.service.UserChatService;
import com.example.boot.redis.RedisManager;
import io.netty.channel.Channel;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
@Service("userChatService")
public class UserChatServiceImpl  extends ServiceImpl<UsersMapper, Users> implements UserChatService {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private UsersMapperCustom usersMapperCustom;
    @Autowired
    private ChatMsgMapper chatMsgMapper;
    @Resource
    private RedisManager redisManager;
    @Value("${rocketmq.producer.topic}")
    private String topic;
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public String saveMsg(ChatMessage chatMsg) {

        ChatMsg msgDB = new ChatMsg();

        msgDB.setAcceptUserId(chatMsg.getReceiverId());
        msgDB.setSendUserId(chatMsg.getSenderId());
        msgDB.setCreateTime(new Date());
        msgDB.setSignFlag(MsgSignFlagEnum.unsign.type);
        msgDB.setMsg(chatMsg.getMsg());

        chatMsgMapper.insert(msgDB);

        return msgDB.getId();
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void updateMsgSigned(List<String> msgIdList) {
        usersMapperCustom.batchUpdateMsgSigned(msgIdList);
    }
    @Override
    public void rocketMQMsgText(String msgText) {
        //rocketMQTemplate.convertAndSend(msgText);
        rocketMQTemplate.syncSend(topic, msgText);
    }
    @Override
    public  void set(String senderId, String channel) {
        redisManager.set(senderId, channel,60);
    }

    @Override
    public String get(String receiverId) {
        return  redisManager.get(receiverId);
    }
}
